package com.king.juc.atomicdemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

import static com.king.juc.utils.ThreadUtil.sleep;

/**
 * 模拟cas锁
 * @author king
 * @date 2020/12/2 22:51
 */
@Slf4j(topic = "c.LockCas")
public class LockCas {
    private static AtomicInteger state = new AtomicInteger(0);

    public static void main(String[] args) {
        LockCas lock = new LockCas();
        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try{
                log.debug("lock....");
                sleep(1);
            }finally {
                lock.unlock();
            }
        }).start();
        new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try{
                log.debug("lock....");
                sleep(1);
            }finally {
                lock.unlock();
            }
        }).start();
    }

    private void lock(){
        while(true){
            if(state.compareAndSet(0, 1)){
                break;
            }
        }
    }

    private void unlock(){
        log.debug("unlock....");
        state.set(0);
    }

}
